<?php

namespace app\controller;

use app\BaseController;
use app\model\Character;
use app\model\User_character;

/**
 * 会员
 * Class User
 * @package app\controller
 * @author 下雨吧จุ๊บ
 */
class User extends BaseController
{
    /**
     * @apiGroup 会员
     * @apiVersion 1.0.0
     * @api {GET} /user  用户列表
     * @apiDescription 用户列表
     * @apiParam {String} listRows 每页数量(必填*)
     * @apiParam {String} page 当前页数(必填*)
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * data: 用户列表,
     * message: '获取用户列表成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function index()
    {
        $data = input();
        if (empty($data['listRows'])) {
            $data['listRows'] = '8';
        }
        if (empty($data['page'])) {
            $data['page'] = '1';
        }
        $map[] = ['username','like','%%'];
        if (!empty($data['map']['title'])){
            $map[] = ['username','like','%'. $data['map']['title'] .'%'];
        }
        if (!empty($data['map']['characterid'])){
            $ids = User_character::where('characterid',$data['map']['characterid'])->select();
            $idinarr = array();
            if (!empty($ids)){
                foreach ($ids as $k=>$v){
                    $idinarr[$k] = $v['userid'];
                }
            }
            $map[] = ['id','in',$idinarr];
        }
        $data['list'] = \app\model\User::where($map)
            ->paginate([
            'list_rows' => $data['listRows'],
            'page' => $data['page'],
        ]);
        $data['character'] = Character::where('status', 1)->select();
        success($data, '获取用户列表成功');
    }

    /**
     * @apiGroup 会员
     * @apiVersion 1.0.0
     * @api {GET} /user/create  新增
     * @apiDescription 新增会员界面
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * data: 部门列表,
     * message: '获取数据成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function create()
    {
        $data['character'] = Character::where('status', 1)->select();
        success($data, '获取数据成功');
    }

    /**
     * @apiGroup 会员
     * @apiVersion 1.0.0
     * @api {POST} /user  新增保存
     * @apiDescription 新增保存
     * @apiParam {String} username 用户名(必填*)
     * @apiParam {String} password 密码(必填*)
     * @apiParam {String} realname 真实姓名
     * @apiParam {String} sex 性别
     * @apiParam {String} phone 手机
     * @apiParam {String} email 邮箱
     * @apiParam {array} character 所属部门(部门id集合)
     * @apiParam {String} department 所属部门
     * @apiParam {String} status 状态
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * message: '新增成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function save()
    {
        $data = input();
        //必填项验证
        if (empty($data['username'])) {
            error('请输入用户名');
        }
        if (empty($data['password'])) {
            error('请输入密码');
        }
        if (empty($data['character'])){
            error('请选择所属部门');
        }
        //重复验证
        $is_setUser = \app\model\User::where('username', $data['username'])->field('id')->find();
        if (!empty($is_setUser)) {
            error('该账号已存在');
        }
        $is_setUserrealname = \app\model\User::where('realname', $data['realname'])->field('id')->find();
        if (!empty($is_setUserrealname)) {
            error('该用户名已被使用');
        }
        for ($i = 0; $i < 1; $i--) {
            //生成token
            $data['token'] = createToken();
            //判断是否唯一
            $is_setToken = \app\model\User::where('token', $data['token'])->field('id')->find();
            if (empty($is_setToken)) {
                break;
            }
        }
        //密码加密
        $data['password'] = md5($data['password']);
        $characters = $data['character'];
        unset($data['character']);
        //添加数据
        $result = \app\model\User::insertGetId($data);
        if ($result) {
            //用户关联部门
            foreach ($characters as $v) {
                $insertUserCharacter['userid'] = $result;
                $insertUserCharacter['characterid'] = $v;
                User_character::insert($insertUserCharacter);
            }
            success(array(), '新增成功');
        }
        error('新增失败');
    }

    /**
     * @apiGroup 会员
     * @apiVersion 1.0.0
     * @api {GET} /user/:id  编辑读取
     * @apiDescription 编辑页面(:id是指当前id,直接写在路由中)
     * @apiParam {String} id 用户id
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * data: array
     * message: '获取数据成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function read()
    {
        $data = input();
        //必填项验证
        if (empty($data['id'])) {
            error('520数据错误(Missing parameter id)');
        }
        //部门列表
        $data['character'] = Character::where('status', 1)->select();
        //返回会员详情
        $data['info'] = \app\model\User::where('id', $data['id'])->find();
        $data['info']['characterid'] = User_character::where('userid', $data['info']['id'])->find()['characterid'];
        success($data, '获取数据成功');
    }

    /**
     * @apiGroup 会员
     * @apiVersion 1.0.0
     * @api {PUT} /user/:id  编辑保存
     * @apiDescription 编辑页面保存(:id是指当前id,直接写在路由中)
     * @apiParam {String} id 用户id
     * @apiParam {String} username 用户名(必填*)
     * @apiParam {String} password 密码(必填*)
     * @apiParam {String} realname 真实姓名
     * @apiParam {String} sex 性别
     * @apiParam {String} phone 手机
     * @apiParam {String} email 邮箱
     * @apiParam {String} character 所属部门(部门id)
     * @apiParam {String} department 部门职位
     * @apiParam {String} status 状态
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * message: '保存成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function update()
    {
        $data = input();
        //必填项验证
        if (empty($data['id'])) {
            error('520数据错误(Missing parameter id)');
        }
        if (empty($data['username'])) {
            error('请输入用户名');
        }
        if (empty($data['character'])){
            error('请选择所属部门');
        }
        //首先调取当前信息
        $info = \app\model\User::where('id', $data['id'])->find();
        if ($info['username'] != $data['username']){
            //重复验证
            $is_setUser = \app\model\User::where('username', $data['username'])->field('id')->find();
            if (!empty($is_setUser)) {
                error('该账号已存在');
            }
        }
        if ($info['realname'] != $data['realname']){
            $is_setUserrealname = \app\model\User::where('realname', $data['realname'])->field('id')->find();
            if (!empty($is_setUserrealname)) {
                error('该用户名已被使用');
            }
        }
        //更新所属部门
        $characters = $data['character'];
        unset($data['character']);
        //删除关联部门
        User_character::where('userid', $data['id'])->delete();
        //重新关联部门
        foreach ($characters as $v) {
            $insertUserCharacter['userid'] = $data['id'];
            $insertUserCharacter['characterid'] = $v;
            User_character::insert($insertUserCharacter);
        }
        //不填写则不修改密码
        if (empty($data['password'])){
//            $data['password'] = cache($_SESSION['token']['value'])['password'];
            unset($data['password']);
        }else{
            $data['password'] = md5($data['password']);
        }
        //更新会员数据
        $result = \app\model\User::where('id', $data['id'])->save($data);
        success(array(), '保存成功');
    }

    /**
     * @apiGroup 会员
     * @apiVersion 1.0.0
     * @api {DELETE} /user/0  删除
     * @apiDescription 删除(路由中直接写0,ids集合使用参数传递)
     * @apiParam {array} ids id集合
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * message: '删除成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function delete()
    {
        $data = input();
        //必填项验证
        if (empty($data['ids'])) {
            error('520数据错误(Missing parameter id)');
        }
        //超级管理员验证
        foreach ($data['ids'] as $k=>$v){
            if ($v == 1){
                unset($data['ids'][$k]);
            }
        }
        $result = \app\model\User::whereIn('id', $data['ids'])->delete();
        success(array(), '删除成功');
    }

    /**
     * @apiGroup 会员
     * @apiVersion 1.0.0
     * @api {GET} /user/:id/edit  修改密码
     * @apiDescription 修改密码(:id是指当前id,直接写在路由中)
     * @apiParam {String} id 用户id
     * @apiParam {String} oldpassword 老密码
     * @apiParam {String} newpassword 新密码
     * @apiParam {String} confirmpassword  确认密码
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * message: '修改成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function edit()
    {
        $data = input();
        //必填项验证
        if (empty($data['id'])) {
            error('520数据错误(Missing parameter id)');
        }
        if (empty($data['oldpassword'])) {
            error('请输入旧密码');
        }
        if (empty($data['newpassword'])) {
            error('请输入新密码');
        }
        if (empty($data['confirmpassword'])) {
            error('请再次输入新密码');
        }
        //验证
        if ($data['newpassword'] != $data['confirmpassword']){
            error('两次输入密码不一致');
        }
        //校验完成,判断旧密码是否正确
        $info = \app\model\User::where('id',$data['id'])->find();
        if ($info['password'] != md5($data['oldpassword'])){
            error('旧密码错误');
        }
        //修改密码
        $edit['password'] = md5($data['newpassword']);
        //更新会员数据
        $result = \app\model\User::where('id', $data['id'])->save($edit);
        if ($result){
            $_SESSION['token']['time'] = '';
            success(array(),'密码修改完成');
        }
        error('新密码与旧密码相同');
    }
}
